<?php
namespace app\common\command;

use app\common\model\shop\PlatformModel;
use app\common\model\shop\self\SelfGoodsCategoryModel;
use app\common\model\shop\ShopsModel;
use app\common\service\CrmebService;
use think\admin\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

/**
 * 自有平台异步任务
 * @Description
 * @author wangqinghui
 * @date 2025-01-09 15:05
 */
class SelfAttributeCommand extends Command
{

    /**
     * configure
     * @Description 配置
     * @author wangqinghui
     * @date 2024-11-18 10:14
     * @return void
     */
    protected function configure()
    {
        $this->setName('selfAttribute')->addArgument('action', Argument::OPTIONAL, 'action', '')
        ->addArgument('paramId', Argument::OPTIONAL, 'category id or account id', '')
        ->setDescription('sync pull self category');
    }

    /**
     * 执行命令
     * @param \think\console\Input $input
     * @param \think\console\Output $output
     * @Description
     * @author wangqinghui
     * @date 2025-01-09 15:11
     * @return void
     */
    protected function execute(Input $input, Output $output)
    {
        $action = trim($input->getArgument('action'));
        $action = strtolower($action);
        $param_id = $input->getArgument('paramId');
        $this->setQueueProgress('action '.$action. ' start');
        switch ($action) {
            case 'category':// 分类
                $this->pullCategoryList((int) $param_id);
                break;
            default:
                break;
        }
        $this->setQueueSuccess('action '.$action. ' end');
    }

    /**
     * 拉取商品分类
     * @Description
     * @author wangqinghui
     * @date 2024-11-19 15:49
     * @return void
     */
    protected function pullCategoryList(int $account_id)
    {
        if(empty($account_id) || ($account_id <= 0)){
            $this->setQueueError('公司有误');
        }

        $shop_info = $this->_getShopInfo($account_id);
        if(empty($shop_info)){
            $this->setQueueError('店铺不存在');
        }

        // 获取兹有平台接口服务
        $crmeb_service = CrmebService::getInstance();
        $res = $crmeb_service->setConfig($shop_info)->getToken()->getCategoryList();
        if(empty($res['code']) || ($res['code'] != 1)){
            $this->setQueueError('获取分类失败:'.$crmeb_service->getError());
        }

        if(empty($res['data'])){
            $this->setQueueError('暂无分类');
        }

        $list = $res['data'];

        $cate_ids = array_column($list, 'id', 'id');

        // 获取现有分类数据
        $map = [
            ['account_id', '=', $account_id]
        ];
        $old_category_list = SelfGoodsCategoryModel::mk()->where($map)->column('id', 'cate_id');

        $del_ids = array_diff_key($old_category_list, $cate_ids);
        if(!empty($del_ids)){
            SelfGoodsCategoryModel::mk()->where('id', 'in', $del_ids)->delete();
        }

        $act_user_id = $this->queue->data['act_user_id'] ?? 0;

        $add_data = [];
        foreach ($list as $key => $value) {
            if(!empty($old_category_list[$value['id']])){
                $edit_id = $old_category_list[$value['id']];
                $update_data = [
                    'pid'   =>  $value['pid'],
                    'cate_id'   =>  $value['id'],
                    'name'   =>  $value['cate_name'],
                    'sort'   =>  $value['sort'],
                    'is_show'   =>  $value['is_show'],
                    'picture'   =>  $value['pic'],
                    'big_picture'   =>  $value['big_pic'],
                ];
                SelfGoodsCategoryModel::mk()->where('id', $edit_id)->update($update_data);
            }else{
                $temp = [
                    'account_id'   =>  $account_id,
                    'pid'   =>  $value['pid'],
                    'cate_id'   =>  $value['id'],
                    'name'   =>  $value['cate_name'],
                    'sort'   =>  $value['sort'],
                    'is_show'   =>  $value['is_show'],
                    'picture'   =>  $value['pic'],
                    'big_picture'   =>  $value['big_pic'],
                    'user_id'   =>  $act_user_id,
                ];
                $add_data[] = $temp;
            }
        }
        if(!empty($add_data)){
            SelfGoodsCategoryModel::mk()->insertAll($add_data);
        }
        $this->setQueueSuccess('同步分类成功');
    }

    /**
     * 获取商户下的店铺信息
     * @param integer $account_id
     * @Description
     * @author wangqinghui
     * @date 2025-01-09 15:27
     * @return array
     */
    private function _getShopInfo(int $account_id): array
    {
        // 获取自有平台的平台ID
        $map = [
            ['status', '=', 1],
            ['code',     '=', PlatformModel::SELF_CODE],
        ];
        $platform_id = PlatformModel::mk()->where($map)->value('id');
        if(empty($platform_id)){
            $this->setQueueError('平台不存在');
        }
        // 获取自有平台下店铺
        $map = [
            ['platform_id',  '=', $platform_id],
            ['status',   '=', 1],
            ['is_deleted',   '=', 0],
            ['account_id',   '=', $account_id]
        ];
        $shop_info = ShopsModel::mk()->where($map)->find();
        if(empty($shop_info)){
            $this->setQueueError('店铺不存在');
        }
        return $shop_info->toArray();
    }
}